<template>
	<view class="bodyView" :data-theme="dataTheme">
		<view class="mapView">

			<view class="top">
				<navPhoneBar></navPhoneBar>
				<view class="back" @click="handleBack">
					<image class="topImg" src="@/static/icons/arrowLeft.png" mode=""></image>
				</view>

			</view>

			<map id="homemap" show-location :scale="defaultScale" :latitude="location[1]" :longitude="location[0]"
				:polyline="polyline" :markers="markers" @markertap.stop.prevent="handleMarkertap"
				@tap.self="handleMapTap" :polygons="polygons" >
				<!-- :polygon="polygons" -->
				<!--自定义冒泡-->
				<cover-view slot="callout">
					<cover-view v-for="(item) in markers" :key="item.id" class="customCallout" :marker-id="item.id">
						<cover-view class="txt">{{item?.phone||'未知用户'}}</cover-view>
					</cover-view>
				</cover-view>

			</map>

			<view :class="{routerInfo:true,show:routerInforShow}">
				<view>距离：{{routerInfo?.distance}}（米）</view>
				<view class="">
					时间：{{routerInfo?.duration}}（分）
				</view>
				<view class="" @click="openNav">
					打开导航
				</view>
			</view>

			<view class="sideTool">
				<view class="AInav" @click="aiNav">
					<text>智能</text>
					<text>规划</text>
				</view>
			</view>

		</view>


		<uni-popup ref="popup" type="bottom" mas border-radius="40px 40px 0 0">
			<view class="orderDetail">
				<view class="label">订单</view>
				<view class="option pro">
					<view class="producs">
						<view v-for="detail in popData?.producJson" class="producImg" @click="showProduc(detail.id)"
							:style="`background-image:url(./static/cake/${detail.image});`"> </view>
					</view>
					<view class="address" @click="mapNavgator(popData)">
						<view class="">
							<text>地址：</text> {{popData?.latitude}}|{{popData?.longitude}}
						</view>
						<uni-icons type="paperplane-filled" color="#e18092" size="26"></uni-icons>

					</view>
					<view class="bottomInfo">
						<view class="left">
							{{parseTime(new Date(popData?.dateTime))}}
						</view>
						<view class="right">
							${{popData?.money}}
						</view>
					</view>

				</view>
			</view>

		</uni-popup>
	</view>
</template>

<script setup>
	import {searchAddress} from '@/hooks/mapHooks.js'
	let {
		navFun,
		qqmapsdk,
		initMapSdk
	} = searchAddress() 
	import {
		onMounted,
		ref
	} from 'vue';
	import {
		parseTime
	} from "@/utils/tool.js"
	import {
		getSendIngOrders
	} from '@/api/index.js'
	import useSystemStore from '@/store/modules/system'
	const systemStore = useSystemStore()
	const {
		dataTheme,
	} = storeToRefs(systemStore); 
	//popup组件
	let popup = ref(null)
	let popData = ref(null)
	//地图对象
	let mapContext = null
	//默认缩放
	let defaultScale = ref(14)
	//默认坐标
	let location = ref([116.397128, 39.916527])
	//打点坐标
	let markers = ref([{
		id: 1,
		latitude: 30.41875,
		longitude: 120.25553699144416,
		//title: '点位名称',
		iconPath: '../../static/icons/cake.png',
		width: 30,
		height: 30,
		customCallout: {
			display: 'BYCLICK',
			anchorY: -10
		}
	}])
	//polyline
	let polyline = ref([])
	//点击标记锁
	let markerTapLock = false
	let markerTapLockTimeOut = null
	//是否显示导航详情
	let routerInforShow = ref(false)
	let routerInfo = ref({})
	//区域多边形
	let polygons=ref([
		{
			points:[
				{longitude:120.25553699,latitude: 30.41875},
				{longitude:120.29953699,latitude: 30.42885},
				{longitude:120.29953699,latitude: 30.40885},
				{longitude:120.25553699,latitude: 30.41875}, 
			],
			strokeWidth:4,
			strokeColor:'#6fba74',
			fillColor:'rgba(129,217,134,0.3)',
		}
	])




	//打开导航
	let openNav = () => {
		 
		let pram = {
			location:`${routerInfo.value.latitude},${routerInfo.value.longitude}`,
			success: (res) => {
				//console.log(res); 
				mapContext.openMapApp({
					latitude: Number(routerInfo.value.latitude) ,
					longitude:  Number(routerInfo.value.longitude),
					destination:res.result.address,
					success: function() {
						console.log('success');
					},
					fail:(e)=>{
						console.log(e);
					}
				});
			},
			fail: (error) => {
				console.error(error);
				 
			},
			complete: (res) => {
				console.log(res);
				 
			}
		}
		qqmapsdk.reverseGeocoder(pram)
		
	} 
	//智能导航
	let aiNav = () => {
		let _waypoints = markers.value.reduce((o, c) => {
			if (o.indexOf(c.latitude.toString()) >= 0 && o.indexOf(c.longitude.toString()) >= 0)
				return o
			else {
				let _temp = o + ';' + c.latitude.toString() + ',' + c.longitude.toString()
				return _temp
			}
		}, '')

		navFun({
				latitude: location.value[1],
				longitude: location.value[0]
			}, _waypoints.substring(1)).then((data) => {

				console.log(3534, data);
				uni.hideLoading()

				polyline.value = [{
					points: data.pl,
					color: '#6fba74',
					width: 4
				}]

				routerInfo.value = data.ret

				setTimeout(() => {
					routerInforShow.value = true
				}, 300)
			})
			.catch(() => {

			})
	}
	//单点导航
	let mapNavgator = (item) => {
		uni.showLoading()
		navFun(item).then((data) => {
				uni.hideLoading()

				polyline.value = [{
					points: data.pl,
					color: '#6fba74',
					width: 4
				}]
				
				routerInfo.value =Object.assign(data.ret,item) 
				 
				popup.value.close()
				setTimeout(() => {
					routerInforShow.value = true
				}, 300)
			})
			.catch(() => {
				popup.value.close()
			})
	}
	//显示产品详情
	let showProduc = (id) => {
		popup.value.close()
		routerInforShow.value = false
		uni.$emit('showProDetail', id)
	}
	//点图点击
	let handleMapTap = (e) => {
		routerInforShow.value = false
		if (!markerTapLock)
			markers.value.map(row => row.customCallout.display = 'BYCLICK')
	}
	//关闭弹框
	let handleBack = () => {
		uni.navigateBack()
	}
	//marker点击事件
	let handleMarkertap = (e) => {
		routerInforShow.value = false
		markerTapLock = true
		if (markerTapLockTimeOut)
			clearTimeout(markerTapLockTimeOut)
		markerTapLockTimeOut = setTimeout(() => {
			markerTapLock = false
		}, 300)

		markers.value.find((item, index) => {
			if (item.id == e.detail.markerId) {
				mapContext.moveToLocation({
					...item
				})
				item.customCallout.display = 'ALWAYS' // 点击marker 显示地点名
				console.log(item);
				popData.value = item
				popup.value.open()
				// item.width = 32 * 1.5; 
				// item.height = 32 * 1.5;  
			} else {
				item.customCallout.display = 'BYCLICK';
				// item.width = 32;
				// item.height = 32;
			}
		})
	}
	//初始化
	let init = () => {
		mapContext = uni.createMapContext('homemap', this);
		console.log(mapContext);
		uni.getLocation({
			type: "wgs84",

			timeout: 10000,
			success: (res) => {
				const {
					longitude,
					latitude
				} = res;
				location.value = [longitude, latitude];
				// mapContext.addCustomLayer({
				// 	layerId: 'custom_layer_id',
				// 	html: '<div style="color:red;">这是自定义层</div>'
				// });
				mapContext.moveToLocation({
					success: () => { 
						setTimeout(() => {
							mapContext.getCenterLocation({
								success: (res) => {
									const {
										longitude,
										latitude
									} = res;
									console.log(longitude, latitude,
										"当前的地理位置");
									location.value = [longitude, latitude];


								},
								fail: () => {
									uni.showToast({
										title: "定位失败，请重试",
										icon: "none"
									});
								},
							});
						}, 1000);
					},
					fail: (req) => {
						console.log(req, "错误信息");
						 
						uni.showToast({
							title: "定位失败，请重试",
							icon: "none"
						});
					},
				});
			 
			},
			fail: (req) => {
				console.log(req);
				 
				uni.showToast({
					title: "获取位置信息失败，请确认是否开启定位权限",
					icon: "none",
				});
			},
		});

	}
	onMounted(async () => {
		if(!qqmapsdk)
		{
			qqmapsdk=initMapSdk() 
		} 
		 
		init()
		let _re = await getSendIngOrders({})
		if (_re.code == 200) {
			markers.value = _re.data.map(row => ({
				// latitude: 30.41875,
				// longitude: 120.25553699144416, 
				iconPath: '../../static/icons/cake.png',
				width: 30,
				height: 30,
				customCallout: {
					display: 'BYCLICK',
					anchorY: -10
				},
				...row
			}))
		}
	})
</script>

<style lang="scss" scoped>
	.orderDetail {
		box-sizing: border-box;
		width: calc(100vw - $mainPadding * 2);
		height: 45%;
		margin-left: $mainPadding;

		@include useTheme {
			background-color: getValue("bgColor");
			color: getValue("textColor");
		}

		padding: $mainPadding;
		border-radius: 40px;

		.label {
			font-size: $fontSize;
		}

		.option {
			padding: $mainPadding;
			font-size: $fontSize2;
			border-bottom: 1px solid rgba(143, 143, 143, 0.6);
			@include flex-teng(row, space-between);


			&.pro {
				flex-direction: column !important;
				row-gap: 10rpx;
			}

			.bottomInfo {
				width: 100%;
				font-size: $fontSize3;
				@include flex-teng(row, space-between);
			}

			.address {
				width: 100%;
				@include flex-teng(row, space-between);
				margin-bottom: $mainPadding;
			}

			.producs {
				width: 100%;
				display: flex;
				overflow: auto;
				column-gap: 10rpx;

				.producImg {
					min-width: 100rpx;
					height: 100rpx;
					border-radius: 20rpx;
					background-size: cover;
				}
			}
		}

	}

	.customCallout {
		background-color: #fff;
		background: #FFFFFF;
		box-shadow: 0px 8rpx 32rpx 0px rgba(189, 191, 193, 0.4);
		border-radius: 10rpx;
		padding: $mainPadding;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #000 !important;

		.content-image {
			width: 60rpx;
			height: 60rpx;
			margin-left: 10rpx;
		}
	}

	.mapView {
		width: 100vw;
		height: 100vh;

		@include useTheme {
			background-color: getValue("bgColor");
			color: getValue("textColor");
		}

		@include flex-teng(column);

		.top {
			position: absolute;
			width: 100vw;
			top: 0;
			z-index: 111;

			//@include flex-teng(row, space-between);

			.back {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				margin-left: $mainPadding;
				@include flex-teng;

				@include useTheme {
					background-color: getValue("bottombgColor");
				}

				.topImg {
					width: 50rpx;
					height: 50rpx;
				}
			}
		}

		.routerInfo {
			bottom: $mainPadding;
			position: absolute;
			box-sizing: border-box;
			width: calc(100vw - $mainPadding * 2);
			height: auto;
			transform: translateY(300%);
			transition: transform 0.3s cubic-bezier(0.075, 0.82, 0.165, 1);

			&.show {
				transform: translateY(0%);
			}

			@include useTheme {
				background-color: getValue("bgColor");
				color: getValue("textColor");
			}

			padding: $mainPadding;
			border-radius: 40px;
		}

		.sideTool {
			bottom: 400rpx;
			right: $mainPadding;
			position: absolute;
			box-sizing: border-box;
			@include flex-teng(column);

			.AInav {
				border-radius: 50%;
				padding: $mainPadding;
				font-size: $fontSize3;
				@include flex-teng(column);

				@include useTheme {
					background-color: getValue("bgColor");
					color: getValue("textColor");
				}

			}

		}

		#homemap {
			width: 100%;
			height: 100%;
			flex: 1;
		}
	}
</style>